package com.juyu.miliao.api.controller;

import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.dto.FindDynamicInfoDTO;
import com.juyu.miliao.api.domain.vo.*;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import com.juyu.miliao.api.service.AppKeyService;
import com.juyu.miliao.api.service.EnergyLevelService;
import com.juyu.miliao.api.service.FindService;
import com.juyu.miliao.api.service.OpenApiService;
import com.juyu.miliao.common.constant.LocationConstant;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 发现社区
 *
 * @author xuanqicheng
 */
@RestController
@RequestMapping("/find/dynamic")
@CrossOrigin
@Slf4j
public class FindDynamicController {

    @Autowired
    private FindService findService;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private EnergyLevelService energyLevelService;

    @Autowired
    private AppKeyService appKeyService;

    @Autowired
    private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;


    @PostMapping("/")
    public void addFindInfo(Authentication token, @Validated FindDynamicInfoDTO findDynamicInfoDTO,
                            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        Subject subject = (Subject) token.getPrincipal();
        User user = userInfoDao.getUserInfoById(subject.getId());

        String location = findDynamicInfoDTO.getLocation();

        String userLocation = user.getLocation();

        checkLocation(location, userLocation,findDynamicInfoDTO);

        if (user.getSex() == 1 || user.getIsHost() != 1) {
            throw new ConsumeRuntimeException("4001", "非女主播用户", HttpStatus.BAD_REQUEST);
        }

        findDynamicInfoDTO.setUserId(subject.getId());
        findDynamicInfoDTO.setIsHost(user.getIsHost());
        findDynamicInfoDTO.setSex(user.getSex());
        findService.checkFindDynamicDTO(findDynamicInfoDTO);
        findService.addFindDynamicInfo(findDynamicInfoDTO);
    }


    /**
     * 发现列表
     *
     * @param token
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/{page}-{pageSize}")
    public Map<String, Object> getDynamicInfoList(HttpServletRequest request, Authentication token, @PathVariable("page") Integer page,
                                                  @PathVariable("pageSize") Integer pageSize) throws IOException {
        Map<String, Object> map = new HashMap<>(2);
        if (page <= 0) {
            page = 1;
        }
        if (pageSize <= 0) {
            pageSize = 20;
        }
        long userId = 0;
        if (token != null) {
            Subject subject = (Subject) token.getPrincipal();
            userId = subject.getId();
        }
        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        boolean isAudit = openApiService.getAudit(request);
        List<FindDynamicVO> list = findService.getFindDynamicInfoList(userId, page,
                pageSize, isAudit, commonHead.getChannel());
        map.put("list", list);
        return map;
    }

    /**
     * 关注发现动态列表
     *
     * @param token
     * @param page
     * @param pageSize
     * @return
     * @throws IOException
     */
    @GetMapping("/attention/{page}-{pageSize}")
    public Map<String, Object> getAttentionInfo(HttpServletRequest request, Authentication token, @PathVariable("page") Integer page,
                                                @PathVariable("pageSize") Integer pageSize) throws IOException {
        if (page <= 0) {
            page = 1;
        }
        if (pageSize <= 0) {
            pageSize = 20;
        }

        Subject subject = (Subject) token.getPrincipal();
        boolean isAudit = openApiService.getAudit(request);
        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        Map<String, Object> map = findService.getAttentionFindDynamicInfoList(subject.getId(), page,
                pageSize, isAudit,commonHead.getChannel());
        return map;
    }

    /**
     * 附近列表
     *
     * @param location 经纬度,格式为：纬度(lat),经度(lon)
     */
    @GetMapping("/vicinity/{page}-{pageSize}")
    public Object getVicinityInfo(HttpServletRequest request, Authentication token, @PathVariable("page") Integer page,
                                  @PathVariable("pageSize") Integer pageSize, String location) throws IOException {
        if (pageSize <= 0) {
            pageSize = 20;
        }
        if (page <= 0) {
            page = 1;
        }

        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        Subject subject = (Subject) token.getPrincipal();
        boolean isAudit = openApiService.getAudit(request);
        List<FindDynamicVO> list = findService.getVicinityFindDynamicInfoList(subject.getId(), location, page,
                pageSize, isAudit,commonHead.getChannel());
        return list;
    }

    /**
     * 个人发现动态列表
     *
     * @param token
     * @param toUserId 目标用户id
     * @param page
     * @param pageSize
     * @return
     * @throws IOException
     */
    @GetMapping("/individual/{toUserId}/{page}-{pageSize}")
    public List<FindDynamicVO> getIndividualInfo(HttpServletRequest request, Authentication token, @PathVariable("toUserId") Long toUserId, @PathVariable("page") Integer page,
                                                 @PathVariable("pageSize") Integer pageSize) throws IOException {
        if (pageSize <= 0) {
            pageSize = 20;
        }
        if (page <= 0) {
            page = 1;
        }

        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);

        Subject subject = (Subject) token.getPrincipal();

        List<FindDynamicVO> list = findService.getIndividualInfo(subject.getId(), toUserId, page,
                pageSize,commonHead.getChannel());
        return list;
    }

    /**
     * 详情
     *
     * @param token
     * @param findId
     * @return
     * @throws IOException
     */
    @GetMapping("/detail/{findId}")
    public FindDynamicDetailVO getFindDynamicInfo(Authentication token,
                                                  @PathVariable("findId") Integer findId) throws IOException {

        long userId = 0;
        if (token != null) {
            Subject subject = (Subject) token.getPrincipal();
            userId = subject.getId();
        }

        return findService.getFindDynamicDetail(findId, userId);

    }

    @GetMapping("/share/{findId}")
    public FindDynamicShareVO getShareByDynamicId(Authentication token,@PathVariable("findId") Integer findId) throws IOException {
        if (findId == null || findId == 0) {
            throw new ConsumeRuntimeException("动态id不正确");
        }
        Subject subject = (Subject) token.getPrincipal();

        FindDynamicShareVO findDynamicShareVO = findService.getFindDynamicShareInfo(findId);

        Appkey appkey = appKeyService.getAppKeyByKey("shareDynamicObtainEnergy");

        energyLevelService.addUserEnergyLevel(subject.getId(),
                EnergyLevelType.ENERGY_TYPE_SHARE,Integer.parseInt(appkey.getValue()));

        integralRewardsAndPunishmentsHandler.shareMySelfOneDynamic(findId,subject.getId());

        return findDynamicShareVO;
    }


    /**
     * 检查经纬度是否为空
     *
     * @param location     用户实时经纬度
     * @param userLocation 用户数据库中的经纬度
     */
    private void checkLocation(String location, String userLocation,FindDynamicInfoDTO findDynamicInfoDTO) {
        if (StringUtils.isBlank(userLocation)) {
            //如果实时经纬度为空，使用默认经纬度
            if (StringUtils.isBlank(location)) {
                findDynamicInfoDTO.setLocation(LocationConstant.DEFAULT_LATITUDE_AND_LONGITUDE);
            }else{
                check(location);
                findDynamicInfoDTO.setLocation(location);
            }
        } else {
            check(userLocation);
            findDynamicInfoDTO.setLocation(userLocation);
        }



    }

    private void check(String location){
        String[] strs = location.split(",");

        if (strs.length != 2) {
            throw new ConsumeRuntimeException("经纬度格式不正确！");
        } else {
            //纬度(lat),经度(lon)
            String lat = strs[0];
            String lon = strs[1];
            if (StringUtils.isBlank(lat) || StringUtils.isBlank(lon)) {
                throw new ConsumeRuntimeException("经度或纬度为空");
            }
            String mark = "null";
            if (mark.equals(lat) || mark.equals(lon)) {
                throw new ConsumeRuntimeException("经纬度格式不正确！");
            }
        }
    }

}
